package zsh.controller;

import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import zsh.core.Result;
import zsh.domain.Book;
import zsh.service.IBookService;

import java.util.List;

@RestController
@RequestMapping("/book")
@AllArgsConstructor
public class BookController {
    private IBookService bookService;

    @PostMapping
    //开始之前进行参数校验
    public Result<Integer> addBook(@RequestBody Book book) {
        return Result.success(bookService.addBook(book));
    }

    @PutMapping
    public Result<Integer> updateBook(@RequestBody Book book) {
        if (book.getId() == null){
            return Result.error(500,"id不能为空");
        }
        return Result.success(bookService.updateBook(book));
    }

    @PostMapping("/list")
    public Result<List<Book>> getBooks(@RequestBody Book book) {
        return Result.success(bookService.getAllBooks(book));
    }
    @GetMapping("/{id}")
    public Result<Book> selectById(@PathVariable int id) {
        return Result.success(bookService.getBookById(id));
    }

    @DeleteMapping
    public Result<Integer> deleteBook(int id) {
        return Result.success(bookService.deleteBook(id));
    }

    @PostMapping("/listByPage")
    public Result<PageInfo<Book>> getBooksByPage(@RequestBody Book book,
                                                 @RequestParam(defaultValue = "1") int pageNum,
                                                 @RequestParam(defaultValue = "10") int pageSize) {
        PageInfo<Book> pageInfo = bookService.getAllBooksByPage(book, pageNum, pageSize);
        return Result.success(pageInfo);
    }

}
